/**
 * Created with JetBrains PhpStorm.
 * User: Administrator
 * Date: 13-9-17
 * Time: 上午9:21
 * Function:产品发布
 */
    var success_pid = [];
var g = {
    _url: 'call/jh_prod.php',
    r: 0,
    ok:new Array(),
    fails: new Array(),
    save:function(params){
        var that = this;
        $.ajax({url:this._url, type:'POST',dataType:'json',data:params,async:false})
            .done(function(res){
                if(res['errcode']==1000){
                    //console.log(res);
                    that.r += 1;
                    success_pid.push(res['pid']);
                    that.ok.push(params['ttype']);
                } else {
                    that.fails.push(res['msg']);
                }
            })
            .always(function(){
            });
    },
    chk_required:function(){
        var c = 0,
            requiredField = $("#post_frm").contents().find('.required')
                .filter(':visible');
        $.each(requiredField,function(){
            if( $.trim($(this).val())=='' ) {
                alert( $(this).attr('data-msg') );
                $(this).focus();
                c = 1;
                return false;
            }
        });
        return c;
    },
    getChkd:function(obj) {
        var chkd = [], len = obj.length,i=0;
        for(;i<len;i++) {
            chkd.push(obj[i].value);
        }
        return chkd;
    },
    getPrice:function(ttype) {
        var format_price = [];
        var ptr = $("tbody#pof_"+ttype).find('tr'),
            plen = ptr.length,
            i=0;
        for(;i<plen;i++) {
            var price={};
            price.bt = $(ptr[i]).find("input[name='bt_"+ttype+"']").val();
            price.et = $(ptr[i]).find("input[name='et_"+ttype+"']").val();
            price.normalDay = this.getChkd($(ptr[i]).find("input[name='normalDay_"+ttype+"']:checked"));
            price.pg = $(ptr[i]).find("input[name='pg_"+ttype+"']").val();
            price.pl = $(ptr[i]).find("input[name='pl_"+ttype+"']").val();
            price.price1 = $(ptr[i]).find("input[name='pm_"+ttype+"']").val();
            price.storage = $(ptr[i]).find("input[name='sg_"+ttype+"']").val();
			//alert(price.pg);
			//alert(price.pl);
			//alert(price.price1);
           // if(isNaN(price.pg)||isNaN(price.pl)||isNaN(price.price1))
			// { alert("输入价格必须为数字!");window.location.reload();exit();}
		    format_price.push(price);
		//else{format_price.push(price);}
        }
        return format_price;
    },
    date_chkd: function(obj){
        if(!obj) {
            return false;
        }
        var t= parseInt(obj.attr('data-chk')),
            obj_list = obj.parent().find('input.pday');
        switch(t){
            case 1:
                if(obj.hasClass('checked')) {
                    obj_list.removeAttr('checked');
                    obj.removeClass('checked');
                } else {
                    obj_list.attr('checked','checked');
                    obj.addClass('checked');
                }
                break;
            case 2:
                obj_list.removeAttr('checked');
                obj_list.each(function(){
                    if($(this).val()>0 && $(this).val()<6) {
                        $(this).attr('checked','checked');
                    }
                });
                break;
            case 3:
                obj_list.removeAttr('checked');
                obj_list.each(function(){
                    if($(this).val()==0 || $(this).val()==6) {
                        $(this).attr('checked','checked');
                    }
                });
                break;
            default :break;
        }
    }
};
$(document).ready(function(){
    var lastid = $("input[name='lastid']").val();
    $("input.ticket_type_txt").live('keyup',function(){
        var t = $(this).val(),
            $p = $(this).prev(),
            pof = $p.attr('data-ttype');
        $p.val(t);
        $("#pof_t_"+pof).text(t);
    });
    $("#tb_pub").on('click','input.ticket_type',function(){
        var $i =  $(this).next("input:text");
        var pof = $(this).attr('data-ttype');
        if( $(this).attr('checked') ) {
            $i.removeAttr('disabled').addClass('txt_input').focus();
            $("#pof_"+pof).show();
        } else {
            $i.attr('disabled','disabled').removeClass('txt_input');
            $("#pof_"+pof).hide();
        }
    });
    //日期快速选择BOF
    $("a.date_chk").live('click',function(){
        g.date_chkd($(this));
    });
    //日期快速选择EOF
    //短信通知号码填写BOF
    var cancleEdit = function(){
        $("#edit_notify_num").text('修改').removeClass('editing');
        $("input#notify_num").attr('readonly','readonly').removeClass('notify_num_editing');
        $("#cancel_edit_num").hide();
    };
    $("#edit_notify_num").on('click',function(){
        if($(this).hasClass('editing')){
            var phonenum = $("input#notify_num").val();
            $.post('call/jh_prod.php',{'action':'EditNotifyPhonenum',phonenum:phonenum,lastid:lastid})
                .done(function(response){
                    if(response=='ok'){
                        $("#edit_res").text('保存成功').css('color','green').fadeIn('fast').fadeOut(2000);
                        cancleEdit();
                    } else {
                        alert(response);
                    }
                })
                .error(function(){
                    alert('发生错误，无法保存号码');
                });
        } else {
            $("input#notify_num").removeAttr('readonly').addClass('notify_num_editing').focus();
            $(this).text('保存').addClass('editing');
            $("#cancel_edit_num").show();
        }
    });
    $("#cancel_edit_num").on('click',cancleEdit);

    //保存数据BOF
    $("#btn_save").on('click',function(){
        if( g.chk_required() ) {
            return false;
        }
        //$('.blockOverlay').attr('title','单击关闭').click($.unblockUI);
        var chk_ticket = $("input.ticket_type:checked"),
            i=0,
            len=chk_ticket.length,
            ttype,
            ptype = $("input[name='ptype']").val(),
            //reb = parseInt( $("input[name='reb']").val() ),
            ticketinfo = $("input[name='TicketInfo']").val(),
            params = {};

        if(!len) {
            //alert('请选择票类！');
            //return false;
        }
        if(($('#radio2').attr('checked')=='checked' )&&((!$('input[name="order_end"]').val()) || (!$('input[name="order_start"]').val()))){
            alert('有效日期不能为空');
            return false;
        }
        $.blockUI({ message: $('#msg_wrap'), css: { cursor:'pointer',border:'4px solid #CCC'} });
        params['action'] =  'CreateNewTicket';
        params['ptype'] = ptype;
        params['payType'] = $("input[name='payType']:checked").val();
        params['provide_to'] =  $("select[name='provide2']").find("option:selected").val();
        params['saleTime'] =  $("input[name='saleTime']:checked").val();
        params['lastid'] = $("input[name='lastid']").val();
        //台儿庄产品
        if( $("input[name='uuid']").length ) {
            params['uuid'] = $("input[name='uuid']").val();
        }
        if( $("input[name='frma']").length ) {
            params['frma'] = $("input[name='frma']").val();
        }
        params['ticketMedia'] =  $("input[name='ticketMedia']:checked").val();
        //产品有效期
        params['validTime'] = $("input[name='validTime']:checked").val();
        params['vt'] = $("input[name='vt']").val();

        params['earyTime'] =  $("input[name='earyTime']").val();
        params['blimit_low'] = $("input[name='blimit_low']").val();
        params['blimit_up'] = $("input[name='blimit_up']").val();
        params['did'] = $("input[name='apply_did']").val();
        params['reb'] = $("input[name='reb']").val();
        params['reb_type'] = $("select[name='reb_type']").find("option:selected").val();
        params['verify_limit'] = (function(){
            var data = [],obj = $("input[name='verify_limit\[\]']:checked");
            for(var i=0,len = obj.length;i<len;i++){
                data.push(obj[i].value);
            }
            return data;
        })();
        params['cancel_time'] = $("input[name='cancel_time']").val();
        params['order_end'] = $("input[name='order_end']").val();
        params['order_start'] = $("input[name='order_start']").val();
        params['f[dhour]'] =  $("select[name='dhour']").find("option:selected").val();
//        params['f[v_mobile_support]'] = $("input[name='v_mobile_support']:checked").val();
        params['f[v_ID_support]'] = $("input[name='v_ID_support']:checked").val();
        params['f[tourist_info]'] =  $("input[name='tourist_info']:checked").val();
        params['TicketInfo'] =  ticketinfo;
        params['f[confirm_sms]'] = $("input[name='confirm_sms']:checked").val();
        params['sendVoucher'] = $("input[name='sendVoucher']:checked").val();
         params['confirm_wx'] = $("input[name='confirm_wx']:checked").val();
        // alert($("input[name='sendVoucher']:checked").val());
        params['f[manual_verify]'] =  $("input[name='manual_verify']:checked").val();
        if(ptype=='B') {
            params['rdays'] = $("input[name='rdays']").val();
            params['grp_num1'] = $("input[name='grp_num1']").val();
            params['grp_num2'] = $("select[name='grp_num2']").val();
            params['f[startplace]'] = $("input[name='startplace']").val();
            params['f[endplace]'] = $("input[name='endplace']").val();
            params['f[ass_station]'] = $("textarea#ass_station").val();
        } else if (ptype=='A') {
            //console.log( $("input[name='v_time_limit']:checked").val());
            if ($("input[name='v_time_limit']:checked").val()==1) {
                var v1 = $("#v_tl_1").find('option:selected').val(),
                    v2 = $("#v_tl_2").find('option:selected').val();
                if (v1==v2) {
                    alert("验证时间至少间隔1小时");
                    return false;
                }
                params['f[v_time_limit]'] = v1 +'|' + v2
            } else {
                params['f[v_time_limit]'] = 0;
            }
        }
        g.r = 0;//清空计数器
        g.fails = [];//清空失败信息列表
        for(;i<len;i++) {
            ttype = chk_ticket[i].getAttribute('data-ttype');
            params['ttype'] = ttype;
            params['tTitle'] = chk_ticket[i].value;
            params['price1'] = $("input[name='pm_"+ttype+"']").val();
            params['TicketExplain'] =  $("input[name='TicketExplain\["+ttype+"\]']").val();
            params['ticket'] = g.getPrice(ttype);
            g.save(params);
        }
        if(g.r!=len) {
            $("#result_msg").empty().html('<h3>保存数据时发生错误！错误信息：</h3><ul id="fail_msg_lisg"></ul>');
            for(var k=0;k< g.fails.length; k++) {
                $("#fail_msg_lisg").append('<li>'+g.fails[k]+'</li>');
            }
            var ok_len = g.ok.length;
            for(var j=0;j < ok_len;j++) {
                $("tr#tr_tt_"+g.ok[j]).remove();
                $("tr#pof_"+g.ok[j]).remove();
            }
            $(".rowspan").attr('rowspan',7-ok_len);
            $('#confrim_wrap').show();
            $('.closeWrap').click($.unblockUI);
        } else {
            var pids = success_pid.join('|');
            if(!len)
			{ var success_wrap = '<p class="first">&nbsp;&nbsp;恭喜您，保存成功！</p>' +
                '<p class="normal_p"  style="position:relative;left:80px;top:40px;">' +
                '<a class="ui-button ui-button-sorange" href="prodlists.html">确定</a></p>';
            $("#msg_wrap").html(success_wrap);
		    }
			else
            {var success_wrap = '<p class="first">&nbsp;&nbsp;恭喜您，保存成功！</p>' +
                '<p class="second">是否立即配置分销价格？</p><p class="normal_p">' +
                '<a class="ui-button ui-button-sorange" href="release.html?pid='+pids+'">立即配置</a>' +
                '<a class="ui-button ui-button-sorange" href="release_after.html?pid=' +pids+'">以后配置</a></p>';
            $("#msg_wrap").html(success_wrap);}
        }
    });
    var index = parseInt($("input#key_index").val());
    $("table#price_tb").on('click','a.price_add',function(){
        var ttype = parseInt($(this).attr('data-ttype')),
            tbody = $("#pof_"+ttype),
            tpl = $("#template").html()
                .replace(/{key}/g,ttype)
                .replace(/{ticket_title}/g,'')
                .replace(/{price_control}/g,'<a href="javascript:" data-ttype="'+ttype+'" class="price_remove">删除</a>')
                .replace(/{market_price}/g, ''),
            row_span = $("#pof_t_"+ttype).attr('rowspan');
        if($.browser.msie
            &&($.browser.version==6.0||$.browser.version==7.0)) {
            row_span = $("#pof_t_"+ttype)[0].rowSpan;
            $("#pof_t_"+ttype)[0].rowSpan = row_span+1;
        } else {
            $("#pof_t_"+ttype).attr('rowspan',row_span+1);
        }
        tbody.append(tpl);
        index += 1;
    });
    $("a.price_remove").live('click',function(){
        var ttype = $(this).attr('data-ttype'),
            rowspan = parseInt($("#pof_t_"+ttype).attr('rowspan'));
        $("#pof_t_"+ttype).attr('rowspan',rowspan-1);
        $(this).parents('tr').remove();
        index -= 1;
    });

    $("button.ext_property").on('click',function(){
        if($(this).hasClass('open')) {
            $(this).removeClass('open').text('显示');
            $("tbody#ExtendProperty").hide();
        } else {
            $(this).addClass('open').text('隐藏');
            $("tbody#ExtendProperty").show();
        }
    });
    //线路团号预览
    $(".grp_num").bind('keyup change',function(){
        var n1 = $("input[name='grp_num1']").val(),
            n2 = $("select[name='grp_num2']").val(),
            n3 = '',
            d = $("input[name='ser_date']").val();
        if(n2!='') {
            n3 = '-' + n2;
        }
        $("#prev_grp_num").text(n1+d+n3);
    });
    //库存设置
    $("input.storage").live('focus', function(){
        if($(this).val()=='不限') {
            $(this).val('');
        }
    });
    $("input.storage").live('blur', function(){
        if($(this).val()=='') {
            $(this).val('不限');
        }
    });
    $("input[name='v_time_limit']").on('click', function(){
        var v = $(this).val(),
            $span = $("#span_v_time_limit");
        if(v==1) {
            $span.show();
        } else {
            $span.hide();
        }
    });
    $("a.add_ticket_tp").on('click', function(){
        var prv = $(this).parent().prev(),
            row = parseInt(prv.attr('rowspan')),
            new_row = row+ 1,
            tpl = $("#ticket_temlate").html(),
            new_ticket_tp = tpl.replace(/{key}/g, new_row),
            market_price_str = '<input type="text" data-msg="请输入门市价" class="required input-text w40" name="pm_'+new_row+'">',
            ticket_title_str = '<th rowspan="1" id="pof_t_'+new_row+'">&nbsp;</th>',
            price_tpl = $("#template").html()
                .replace(/{key}/g,new_row)
                .replace(/{ticket_title}/g,ticket_title_str)
                .replace(/{price_control}/g,'<a href="javascript:" class="price_add" data-ttype="'+new_row+'">添加</a>')
                .replace(/{market_price}/g, market_price_str),
            new_price_tpl = '<tbody id="pof_'+new_row+'">'+price_tpl+'</tbody>';
        $(this).parent().prev().attr('rowspan',new_row);
        $("#tb_pub").find('tbody').append(new_ticket_tp);
        $("#price_tb").append(new_price_tpl);
		sethash(2);
    });
    $('#confirm_wx').click(function(){
        var lid = $("input[name=lastid]").val();
        $.ajax({
            type:'POST',
            url:  'call/jh_prod.php',
            data: {"action": "config_confirm_wx","lastid":lid},
            dataType:'JSON',
            success: function(result){
                if(result.code==107){
                    alert(result.msg);
                    $('#confirm_wx').removeAttr('checked');
                    $('#confirm_wx0').attr('checked','checked');
                }           
            }
        })
    })
});

